package com.unohacha.qqj.fzdr.main;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.NineGridView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.BaseRVAdapter;
import com.unohacha.qqj.fzdr.adapter.BaseViewHolder;
import com.unohacha.qqj.fzdr.adapter.NineGridViewClickAdapter2;
import com.unohacha.qqj.fzdr.bean.AllCommentBean;
import com.unohacha.qqj.fzdr.imp.MyApplication;
import com.unohacha.qqj.fzdr.imp.MyCallBack;
import com.unohacha.qqj.fzdr.imp.UrlConfig;
import com.unohacha.qqj.fzdr.imp.XUtil;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.mylibrary.base.BaseActivity;
import com.unohacha.qqj.mylibrary.listener.PoponDismissListener;
import com.unohacha.qqj.mylibrary.view.CommentPopWindow;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 全部评论
 */
public class AllCommentsActivity extends BaseActivity implements OnRefreshLoadmoreListener {

    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.home1_title)
    LinearLayout home1Title;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    
    private int page = 1;
    private String supply_cate_id;//分类id
    private String supply_id;//记录id
    private List<AllCommentBean.DataBeanX.DataBean> mDataList = new ArrayList<>();
    private BaseRVAdapter mBaseAdapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_all_comments;
    }

    @Override
    protected void initView() {
        super.initView();
        commonTitle.setText("全部评论");
        commonRightImage.setVisibility(View.VISIBLE);
        commonRightText.setVisibility(View.GONE);
        commonRightImage.setImageResource(R.drawable.ic_all_comment);
        initRefreshLayout();
        if (null != getIntent()){
            supply_cate_id = getIntent().getStringExtra("supply_cate_id");
            supply_id = getIntent().getStringExtra("supply_id");
            getCommentList(supply_cate_id,supply_id);
        }
    }

    private void initRefreshLayout() {
        mRefreshLayout.setOnRefreshLoadmoreListener(this);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(this));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(this));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }
    
    //获取评论列表
    private void getCommentList(String supply_cate_id,String supply_id){
        Map<String,Object> params = new HashMap<>();
        params.put("page",page);
        params.put("supply_cate_id",supply_cate_id);
        params.put("supply_id",supply_id);
        XUtil.Post(UrlConfig.SUPPLY_COMMENT_LIST,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("TAG: getCommentList," , result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")){
                        Gson gson = new Gson();
                        AllCommentBean commentBean = gson.fromJson(result,AllCommentBean.class);
                        if (null != commentBean){
                            if (page == 1){
                                mRefreshLayout.finishRefresh();
                                mRefreshLayout.resetNoMoreData();
                                if (0 != mDataList.size()){
                                    mDataList.clear();
                                }
                                mDataList.addAll(commentBean.getData().getData());
                            }else {
                                mRefreshLayout.finishLoadmore();
                                mBaseAdapter.notifyDataSetChanged();
                            }
                           setBaseAdapter();
                        }
                        
                       
                    }else if (100 == jsonObject.optInt("code")){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }else {
                        
                        if (page == 1){
                            MyToast(jsonObject.optString("message"));
                            if (0 != mDataList.size()){
                                mDataList.clear();
                            }
                            mBaseAdapter.notifyDataSetChanged();
                            mRefreshLayout.finishRefresh();
                            mRefreshLayout.resetNoMoreData();
                        }else {
                            MyToast(getResources().getString(R.string.no_more_data));
                            mRefreshLayout.finishLoadmore();
                            mRefreshLayout.finishLoadmoreWithNoMoreData();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mRefreshLayout.finishRefresh();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private void setBaseAdapter(){
        mBaseAdapter = new BaseRVAdapter(this,mDataList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_comment_list3;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                ImageView store_pic = holder.getImageView(R.id.store_pic);
                TextView user_name_tv = holder.getTextView(R.id.user_name_tv);
                TextView user_report_content = holder.getTextView(R.id.user_report_content);//发布时间
                TextView comment_user = holder.getTextView(R.id.comment_user);//用户评论

                Glide.with(AllCommentsActivity.this).load(mDataList.get(position).getMember_thumb())
                        .error(R.drawable.ic_default_photo).into(store_pic);
                user_name_tv.setText(mDataList.get(position).getMember_no());
                user_report_content.setText(mDataList.get(position).getCreate_time());
                comment_user.setText(mDataList.get(position).getContent());
                
                NineGridView mRecyclerView = holder.getView(R.id.mRecyclerView);//用来展示用户发的图片
                if (null != mDataList.get(position).getReturn_list() && mDataList.get(position).getReturn_list().size() > 0){

                    ArrayList<ImageInfo> imageInfo = new ArrayList<>();
                    List<String> imageDetails = mDataList.get(position).getReturn_list();
                    if (imageDetails != null) {
                        for (String imageDetail : imageDetails) {
                            ImageInfo info = new ImageInfo();
                            info.setThumbnailUrl(imageDetail);
                            info.setBigImageUrl(imageDetail);
                            imageInfo.add(info);
                        }
                    }
                    mRecyclerView.setVisibility(View.VISIBLE);
                    mRecyclerView.setSingleImageSize(300);
                    mRecyclerView.setAdapter(new NineGridViewClickAdapter2(mContext, imageInfo));
                }else {
                    mRecyclerView.setVisibility(View.GONE);
                }
            }

        };
        mRecyclerView.setAdapter(mBaseAdapter);
    }
    
    @OnClick({R.id.common_back,R.id.common_right_image})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                finish();
                break;
            case R.id.common_right_image:
                if (null == commentPopWindow){
                    commentPopWindow = new CommentPopWindow(AllCommentsActivity.this,AllCommentsActivity.this);
                }
                commentPopWindow.showUi("写评论","取消","发布");
                commentPopWindow.showAtLocation(commonRightImage, Gravity.CENTER,0,0);
                handler.sendEmptyMessage(1001);
                commentPopWindow.setConfirmListener(new CommentPopWindow.OnCommentListener() {
                    @Override
                    public void onSure(String content) {
                        //发布评论，同时刷新供应详情信息
                        if (!TextUtils.isEmpty(content) && !TextUtils.isEmpty(supply_cate_id) ) {
                            ToastUtils.showT("发布");
                            supplyComments(1,supply_cate_id,"",content);
                        }else {
                            MyToast("请输入评论内容!");
                            return;
                        }
                    }

                    @Override
                    public void onCancel() {
                        MyToast("取消");
                        commentPopWindow.dismissView();
                    }
                });
                commentPopWindow.setOnDismissListener(new PoponDismissListener(this));
                break;
        }
    }

    //供求评价
    private void supplyComments(int typeid, final String supply_cate_id, String pid, String content){
        Map<String,Object> params = new HashMap<>();
        params.put("token", Prefer.getInstance().getToken());
        params.put("typeid",typeid);
        params.put("supply_cate_id",supply_cate_id);
        params.put("supply_id",supply_id);
        params.put("pid",pid);
        params.put("content",content);
        XUtil.Post(UrlConfig.SUPPLY_COMMENTS,params,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if (1 == jsonObject.optInt("code")){
                        ToastUtils.showT("走到了");
                        getCommentList(supply_cate_id,supply_id);
//                        getSupplyDetailData(id, typeID);
                    }else if (100 == jsonObject.optInt("code")){
                        MyToast(getResources().getString(R.string.login_out));
                        MyApplication.getInstance().gotoLoginActivity();
                    }
                    MyToast(jsonObject.optString("message"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }
        });
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            //在需要弹出软键盘的地方发送msg
            if (msg.what==1001){
                //使用以下代码来弹出软键盘
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
            return false;
        }
    });
                
    
    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page ++;
                getCommentList(supply_cate_id,supply_id);
            }
        },2000);
        
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                page = 1;
                getCommentList(supply_cate_id,supply_id);
            }
        },2000);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
